var API2_PATH = '/apiv2/';
var ASSET_HOST = 'http://www.wattpad.com';
var AVATAR_PATH = 'http://a.wattpad.net/useravatar/';
var COOKIE_DOMAIN = '.wattpad.com';
var FACEBOOK_APP_ID = '2582347323';

if (/staging\.wattpad\.com/.test(location.host)) {
	ASSET_HOST = 'http://staging.wattpad.com';
	AVATAR_PATH = 'http://b.wattpad.net/useravatar/';
	FACEBOOK_APP_ID ='154907773699';
}
else if (/wattpad\.local/.test(location.host)) {
	ASSET_HOST = 'http://wattpad.local';
	AVATAR_PATH = 'http://wattpad.local/useravatar/';
	COOKIE_DOMAIN = '.wattpad.local';
	FACEBOOK_APP_ID ='116915398349448';
}
else if (/pbx\.wattpad\.com/.test(location.host)) {
	ASSET_HOST = 'http://pbx.wattpad.com';
	AVATAR_PATH = 'http://pbx.wattpad.com/useravatar/';
	FACEBOOK_APP_ID ='116915398349448';
}

$(document).ready(function() {
	if (!hasPlaceholderSupport()) {
		$('[placeholder]').each(function () {
			addPlaceholderSupport($(this));
		});
	}

	// removing hash received from Facebook
	if (window.location.hash.indexOf('_=_')!==-1) {
		window.location.hash = window.location.hash.replace(new RegExp("\#(.?)_=_(.?)"), "$1$2");
	}

	// when something is selected in one category dropdown, it is removed from the other category dropdown
	$('#category1, #category2').change(function () {
		var otherId = /1$/.test(this.id) ? 'category2' : 'category1';
		var otherSelect = $('#'+otherId);
		var oldValue = otherSelect[0].value;
		otherSelect.find('option').remove();
		otherSelect.html($('#categoryMaster').html());
		otherSelect.find('option[value='+oldValue+']').attr('selected', 'selected');
		if (this.value==20) {
			var notWattyCats = new Array(2, 10, 13, 16, 17, 19);
			for (var i = 0; i<notWattyCats.length; i++) {
				otherSelect.find('option[value='+notWattyCats[i]+']').remove();
			}
			if (otherSelect.find('option:selected').length==0) {
				otherSelect.find('option').first().attr('selected', 'selected');
			}
		}
		if (this.value!=0) {
			otherSelect.find('option[value='+this.value+']').remove();
		}
		return false;
	});

	$('#togglebg').click(function () {
		var opacity = ($("#content_wrapper").css("opacity")!=1) ? 1 : 0.2;
		$("#content_wrapper").fadeTo("fast", opacity);
	});

	$('#editProfile').click(function () {
		$('#profileview').toggle();
		$('#profileedit').toggle();
		return false;
	});

	$('#changeAvatar').click(function () {
		$('#avatar1').toggle();
		$('#avatar2').toggle();
		return false;
	});

	if ($("#deleteAvatar").length>0) {
		$('#deleteAvatar').click(function () {
			if (confirm(t("Remove your profile picture?"))) {
				document.forms['delavatarform'].submit();
			}
			return false;
		});
	}

	$('#changeBackground').click(function () {
		$('#background1').toggle();
		$('#background2').toggle();
		return false;
	});

	if ($("#deleteBackground").length>0) {
		$('#deleteBackground').click(function () {
			if (confirm(t("Remove your background picture?"))) {
				document.forms['delbgform'].submit();
			}
			return false;
		});
	}

	$('#changeCover').click(function () {
		$('#cover2').toggle();
		$('#cover1').toggle();
		return false;
	});

	if ($("#deleteCover").length>0) {
		$('#deleteCover').click(function () {
			if (confirm(t("Remove this cover?"))) {
				document.forms['groupform'].action = '?editcover=1';
				document.forms['groupform'].submit();
			}
			return false;
		});
	}

    $(".imgHover").hover(
        function () {
            $(this).attr("src", hoverImg($(this).attr("src")));
        },
        function () {
            $(this).attr("src", normalImg($(this).attr("src")));
        }
    );

	$(".shrink").each(function () {
		// if the height of the target element is >= twice its line-height, need to fit to one line
		var lineHeight = $(this).css("line-height").replace('px', '');
		var currentHeight = $(this).height();
		var fontSize = $(this).css("font-size").replace('px', '');
		// keep reducing the size till the text fits in one line
		while (currentHeight>=(lineHeight*2) && fontSize>6) {
			fontSize--;
			$(this).css("font-size", fontSize+'px');
			currentHeight = $(this).height();
		}
	});

	$(window).scroll(function (event) {
		// auto hide the header bar login when scrolling if
		if (!isMobile() && $('#header_login').is(':visible') && $('#header_login').hasClass('transition_complete') && !$('.has_subtabs').hasClass(('main_tab_hover'))) {
			cancelLogin();
		}
		// current x, y-pos
		var y = $(this).scrollTop();

		// add fixed class if y-pos is greater than top of panel
		if (y>0) {
				$('#top_nav').addClass('top_nav_fixed');
		}
		else {
				$('#top_nav').removeClass('top_nav_fixed');
		}
	});

    if ($('.has_subtabs').length>0) {
        $('.has_subtabs').hover(showSubtab, hideSubtab);
        $('.has_subtabs').bind("touchstart click", function() {
            hideSubtab();
            showSubtab($(this));
        });
    }

	// facebook/twitter auto account create
	var $_GET = {};
	document.location.search.replace(/\??(?:([^=]+)=([^&]*)&?)/g, function () {
		function decode(s) {
			return decodeURIComponent(s.split("+").join(" "));
		}
		$_GET[decode(arguments[1])] = decode(arguments[2]);
	});

	$.each($_GET, function (i, val) {
		if (i.indexOf('auto_created_fb')!=-1) {
			$.facebox({ajax:'/dialog/auto_created_account_warning?fb=1' });
		}
		else if (i.indexOf('auto_created_tw')!=-1) {
			$.facebox({ajax:'/dialog/auto_created_account_warning?tw=1' });
		}
	});
});

function showSubtab($e) {
    if ($(this).find('.sub_tabs').length>0) {
        $e = $(this);
    }
    $e.find('.sub_tabs').show();
    $e.addClass('nav_hover');
}

function hideSubtab() {
    $('.sub_tabs').hide();
    $('.nav_hover').removeClass('nav_hover');
}

function cleanHeaderBar() {
	$(".header_login_button").click(function () {
		$("form#toplogin").submit();
	});

	$('#loginlink').click(function () {
		if (!$('#header_login').is(':visible')) {
			$("#header_login").slideDown('fast', function () {
				$("#header_login").addClass('transition_complete');
			});
		}
		else {
			cancelLogin();
		}
	});

	$('#login_cancel').click(function () {
		cancelLogin();
	});

	if (!parent || !parent.topframe) {
		$('.shuffletab').show();
	}
}

function cleanHeaderBarIE6() {
	$('#loginlink').click(function () {
		if (!$('#header_login').is(':visible')) {
			$("#header_login").show('fast', function () {
				$("#header_login").addClass('transition_complete');
			});
		}
		else {
			cancelLogin();
		}
	});
}

function cancelLogin() {
	$(".toplinks").css("padding", "12px 30px");
	$("#header_login").slideUp('fast', function () {
		$("#header_login").removeClass('transition_complete');
	});
}

function searchOnSubmit() {
    ga_track('Discover', 'Title, Subject, Keyword Search', $('#searchinput').val());
    location.href = '/stories/search/'+encodeURIComponent(encodeURIComponent($('#searchinput').val()));
}

function hoverImg(filename) {
    return filename.replace(new RegExp("(.+)\\.(gif|png|jpg)", "g"), "$1_hover.$2");
}

function normalImg(filename) {
    return filename.replace(new RegExp("(.+)_hover\\.(gif|png|jpg)", "g"), "$1.$2");
}

//Altered fanlink click function because current link handler for iOS webApp doesn't detect .live
if (!isWebApp() || !/(iPhone|iPod|iPad)/.test(navigator.userAgent)) {
	$('.fanlink.ajax, .fanlinkx.ajax').live('click', function () {
		$(this).siblings('.fan_spinner').css({ visibility:'visible' });
		var that = this;
		if (/isfacebook/.test($(that).attr('class')) && /add/.test($(this).attr('href'))) {
			facebook_prompt_permission('publish_stream', function () {
				becomeFan(that);
			});
		}
		else {
			becomeFan(that);
		}
		return false;
	});
}
else {
	$('.fanlink.ajax, .fanlinkx.ajax').click(function () {
		$('.fan_spinner').css({ visibility:'visible' });
		var that = $('.fanlink.ajax, .fanlinkx.ajax');
		if (/isfacebook/.test($(that).attr('class')) && /add/.test($(this).attr('href'))) {
			facebook_prompt_permission('publish_stream', function () {
				becomeFan(that);
			});
		}
		else {
			becomeFan(that);
		}
		return false;
	});
}

function becomeFan(link) {
	var url = $(link).attr('href');
	var word = /member/.test($(link).attr('class')) ? 'member' : 'fan';

	if (!$(link).hasClass('disabled')) {
		$(link).addClass('disabled');
		$.ajax({
			type: 'POST',
			url: $(link).attr('href'),
			success: function (response) {
				$('.fan_spinner').hide();
				$('.fan_icon').remove();
				if (url.search('add')!=-1) {
					$("<span>You're a "+word+"!</span>").replaceAll('.fanlink');
					ga_track('Stories', 'Become a '+word);

					if (word==='fan' && $.query.get('ref')==='rec') {
						ga_track('Recommendations', 'User', 'Fan - Profile', 1);
					}
				}
				else {
					$("<span>You're no longer a "+word+"!</span>").replaceAll('.fanlinkx');
					ga_track('Stories', 'Remove '+word);
				}
			},
			error:function (data, status) {
				alert('Error becoming a fan. Please try again.');
				$('.fan_spinner').hide();
				$(link).removeClass('disabled');
			}
		});
	}
}

function updateCharCount() {
	$("#charcount").text($("textarea[name^=about]").val().length);
}

// translates given string
// TODO: to be implemented
function t(str) {
	return str;
}

function ga_track(category, action, label, value) {
	return _gaq.push(['_trackEvent', category, action, label, value]);
}

function read(id, url) {
	if (isWebApp()) {
		window.location = '/'+url;
	}
	else {
		location.href = 'wattpad://www.wattpad.com/read?id='+id;
	}
}

function isMobile() {
	var ua = navigator.userAgent;
	var isMobileSafari = /(iPad|iPhone|iPod)/.test(ua);
	var isAdobeAir = /adobeair/i.test(ua);
	var isAndroid = /android/i.test(ua);
	var isBlackberry = /blackberry/i.test(ua);
    var isKindleFire = /silk/i.test(ua);
	//var isOpera = window.opera && window.opera.buildNumber;

	return (isMobileSafari || isAdobeAir || isAndroid || isBlackberry || isKindleFire);
}

function isWebApp() {
	var url = window.location.href;
	url = url.replace("http://", "");
	var urlExplode = url.split("/");
	var serverName = urlExplode[0];
	if (serverName.indexOf("fb")!=-1 || serverName.indexOf("touch")!=-1) {
		return true;
	}
	return false;
}

function header_fb(appid) {
	FBStatus = new function (params) {
		this.loggedIn = false;
		this.permissions = [];
		this.accessToken = '';
	}();

	window.fbAsyncInit = function () {

		FB.init({ appId:appid, cookie:true });

		FB.Canvas.getPageInfo(function (info) {
			if (info.clientHeight>0) {
				FB.Canvas.scrollTo(0, 0);
				if (location.href.indexOf('/search')!=-1) {
					FB.Canvas.setSize({ height:740 });
				}
				else {
					FB.Canvas.setAutoGrow();
				}
			}
		});

		function sizeChangeCallback() {
			if (location.href.indexOf('/search')!=-1) {
				FB.Canvas.setSize({ height:740 });
			}
			else {
				FB.Canvas.setAutoGrow();
			}
		}

		FB.getLoginStatus(
			function (response) {
				if (response.authResponse) {
					FBStatus.loggedIn = true;
					FBStatus.accessToken = response.authResponse.accessToken;
					FB.api('/me/permissions', function (response) {
						if (response.data) {
							FBStatus.permissions = response.data[0];
						}
					});
				}
			}, { scope:'' }
		);

		window.facebook_prompt_permission = function (permissions, callback) {
			var hasPermissions = true;
			var permsArray = permissions.split(',');
			for (var i = 0; i<permsArray.length; i++) {
				if (!FBStatus.permissions[permsArray[i]]) {
					hasPermissions = false;
					break;
				}
			}

			if (!FBStatus.loggedIn || !hasPermissions) {
				FB.login(function (response) {
					if (response.authResponse) {
						ga_track('Facebook', 'Login', 'Allow');
						FBStatus.accessToken = response.authResponse.accessToken;
						return callback();
					}
					else {
						ga_track('Facebook', 'Login', "Don't Allow");
						return false;
					}
				}, { scope:permissions });
			}
			else {
				callback();
			}
		}
	};

	(function () {
		var e = document.createElement('script');
		e.src = document.location.protocol+'//connect.facebook.net/en_US/all.js';
		e.async = true;
		document.getElementById('fb-root').appendChild(e);
	}());
}

function header_png() {
	DD_belatedPNG.fix('div.png_bg, div.column_head, div.commentby, div.commentbyauthor, img');
	$(document).bind("beforeReveal.facebox", function () {
		$("select").hide();
	});
	$(document).bind("close.facebox", function () {
		$("select").show();
	})
}

function hasPlaceholderSupport() {
	var i = document.createElement('input');
	return 'placeholder' in i;
}

function addPlaceholderSupport(element) {
	var placeholder_text = $(element).attr('placeholder');

	if (!$(element).val().length) {
		$(element).css('color', '#999').val(placeholder_text);
	}

	$(element).focus(function () {
		if ($(element).val()===placeholder_text) {
			$(element).css('color', '').val('');
		}
	});

	$(element).blur(function () {
		if (!$(element).val().length) {
			$(element).css('color', '#999').val(placeholder_text);
		}
	});
}

function library(storyID) {
	if (!isMobile()) {
		$.facebox({ajax:'/dialog/library?id='+storyID});
	}
	else {
		location.href = '/dialog/library?mobile=1&id='+storyID;
	}
}

function expandStoryCover(id, ownerid, isGroup) {
	$.facebox({ajax:'/dialog/story_cover?id='+id+'&ownerid='+ownerid+'&is_group='+isGroup}, 'coverfull');
}

function trackCategory(catid) {
	cat = $.parseJSON($.cookie("cat"));
	if (!$.isArray(cat)) {
		cat = new Array();
	}

	if (cat[catid]==null) {
		cat[catid] = 1;
	}
	else {
		cat[catid]++;
	}

	for (var i = 0; i<cat.length; i++) {
		if (cat[i]==null) {
			cat[i] = 0;
		}
	}

	$.cookie("cat", JSON.stringify(cat), { expires:60*60*24*30, domain:COOKIE_DOMAIN, path:'/' });
}

function trackRecommendations(linkid) {
	$(linkid).each(function () {
		$(this).attr('href', $(this).attr('href')+'?recommended=1');
	});
	$(linkid).click(function () {
		ga_track('Recommendations', 'click', $(this).text());
		return true;
	});
}